<template>
  <div class="table-wrap" style="height: 400px" @click.stop>
    <div class="btn-wrap">
      <el-button :disabled="!sectionRows.length" :icon="CircleCheckFilled" type="primary" @click="onHandleConfirmSelection">
        确认选择
      </el-button>
    </div>
    <vxe-table
      align="center"
      :auto-resize="true"
      :border="true"
      :data="tableData.datalist"
      :height="300"
      :max-height="tableData.maxHeight"
      :row-config="{ useKey: true }"
      show-header-overflow="tooltip"
      :show-overflow="true"
      :stripe="true"
      @checkbox-all="handleSelectionChange"
      @checkbox-change="handleSelectionChange"
      @sort-change="handleSorted"
    >
      <vxe-column type="checkbox" width="60px" />
      <vxe-column label="序号" type="seq" width="60px" />
      <template v-for="item in tableData.columnList" :key="item.value">
        <vxe-column
          :field="item.value"
          :show-overflow="item.overflow"
          :sortable="!!item.sortable"
          :title="item.label"
          :width="item.width"
        >
          <template #default="{ row }">
            <template v-if="row && row.senum && row.senum[item.value]">
              <span :style="{ color: row.senum[item.value].color }">
                {{ row.senum[item.value].names }}
              </span>
            </template>
            <template v-else>{{ row[item.value] }}</template>
          </template>
        </vxe-column>
      </template>
    </vxe-table>
  </div>
</template>

<script>
import { queryList, doSorted } from "@/api/mains";
import { CircleCheckFilled } from "@element-plus/icons-vue";
export default defineComponent({
  name: "DynamicTableSelect",
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    isFocusing: {
      type: Boolean,
      default: false
    },
    keywords: {
      type: String,
      default: ""
    },
    dynamicConfig: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },

  emits: {
    "update:model-value": null,
    "on-handle-confirm-selection": null
  },

  setup(props, { emit }) {
    const { columnList, url, paramsField = "title" } = props.dynamicConfig.selectTable || {};

    const isVisible = ref(props.modelValue);
    const sectionRows = ref([]);
    const tableData = reactive({
      border: true,
      maxHeight: 300,
      datalist: [],
      isShowPagination: true,
      showSummary: false,
      total: 0,
      isSelectRow: true,
      isLoading: false,
      columnList: columnList || []
    });
    /**
     * 点击非当前组件区域，关闭table
     */

    const bodyCloseTable = () => {
      if (isVisible.value == true) {
        isVisible.value = false;
        emit("update:model-value", isVisible.value);
      }
    };

    /**
     * 搜索词节流
     */
    const delay = (function () {
      let timer = 0;
      return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
      };
    })();

    /**
     * 点击table排序
     * @param {} val
     */
    const handleSorted = async sortValue => {
      const { field, order } = sortValue.column;
      const val = {
        prop: field,
        order: order === "desc" ? "descending" : order
      };

      doSorted(val, queryForm.value);
      fetchData();
    };

    const handleSelectionChange = val => {
      const { records = [] } = val || {};
      sectionRows.value = records;
    };

    const onHandleConfirmSelection = () => {
      emit("on-handle-confirm-selection", sectionRows.value);
      isVisible.value = false;
      emit("update:model-value", isVisible.value);
    };

    watch(
      () => props.keywords,
      () => {
        if (!props.isFocusing) return;
        delay(() => {
          fetchData();
        }, 500);
      }
    );

    /**
     * 获取数据
     */
    const fetchData = async () => {
      isVisible.value = true;
      emit("update:model-value", isVisible.value);
      tableData.datalist = [];
      const res = await queryList(url, {
        [paramsField]: props.keywords
      });
      if (res.code == 200) {
        tableData.datalist = res.data.rows;
      }
    };

    /**
     * 加上事件
     */
    onMounted(() => {
      document.addEventListener("click", bodyCloseTable);
    });

    /**
     * 移除事件
     */
    onUnmounted(() => {
      document.removeEventListener("click", bodyCloseTable);
    });

    return {
      tableData,
      sectionRows,
      handleSorted,
      handleSelectionChange,
      onHandleConfirmSelection,
      CircleCheckFilled
    };
  }
});
</script>

<style lang="scss" scoped>
.table-wrap {
  .btn-wrap {
    margin-bottom: 15px;
    text-align: right;
  }
}
</style>
